<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\OverSeasBa;

use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\OverSeasBa\DropshippingLog;
use App\Models\OverSeasBa\InventoryBox;
use App\Models\OverSeasBa\BoxTranLog;
use App\Models\OverSeasBa\InventoryBoxFNSku;
use Illuminate\Support\Facades\DB;
class BoxAjax {

    /**
     * 换标
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function transfer($param){
        try{
            $detail = $param['detail'];
            $exist = [];
            $_detail = [];
            foreach ($detail as $item){
                $id = $item['id'];
                if(array_key_exists($id,$exist)){
                    $exist[$id] += $item['transfer_num'];
                }else{
                    $exist[$id] = $item['transfer_num'];
                }
                $__detail['account_id'] = $item['account_id'];
                $__detail['fnsku'] = $item['fnsku'];
                $__detail['transfer_num'] = $item['transfer_num'];
                $_detail[$id]['detail'][] = $__detail;
                $_detail[$id]['total'] = $exist[$id];
            }
            $msg = [];
            foreach($_detail as $id => $item){
                $temp = $item['detail'];
                $total = $item['total'];
                DB::beginTransaction();
                $iBox = InventoryBox::query()->lockForUpdate()->find($id);
                if(!$iBox){
                    DB::rollBack();
                    continue;
                }
                $iBoxFnSkuO = InventoryBoxFNSku::query()
                    ->where('account_id',$iBox->account_id)
                    ->where('warehouse_id',$iBox->warehouse_id)
                    ->where('fnsku',$iBox->fnsku)
                    ->first();
                if(!$iBoxFnSkuO){
                    DB::rollBack();
                    continue;
                }
                $instantO = $total * $iBox->num_per_box;
                if($iBoxFnSkuO->instant < $instantO){
                    DB::rollBack();
                    continue;
                }
                $iBoxFnSkuO->instant -= $instantO;
                $iBoxFnSkuO->save();
                $instant = $iBox->storage_total - $iBox->out_total;
                if($instant < $total){
                    $msg[] = $iBox->fnsku;
                    DB::rollBack();
                    continue;
                }
                $count = 0;
                foreach($temp as $_temp){
                    $accountId = $_temp['account_id'];
                    $fnsku = $_temp['fnsku'];
                    $transferNum = $_temp['transfer_num'];
                    $iBoxNo = $iBox->box_no;
                    if($fnsku == $iBox->fnsku){
                        $box_no = InventoryBox::query()
                            ->where('warehouse_id',$iBox->warehouse_id)
                            ->where('batch_no',$iBox->batch_no)
                            ->max('box_no');
                        $iBoxNo = $box_no + 1;
                    }
                    $ici = InventoryBox::query()
                        ->where('batch_no',$iBox->batch_no)
                        ->where('warehouse_id',$iBox->warehouse_id)
                        ->where('box_no',$iBoxNo)
                        ->where('fnsku',$fnsku)
                        ->first();
                    if($ici){
                        $ici->storage_total += $transferNum;
                        $ici->save();
                    }else{
                        InventoryBox::query()
                            ->create([
                                'batch_no' => $iBox->batch_no,
                                'box_no' => $iBoxNo,
                                'fnsku' => $fnsku,
                                'delivery_box_id' => $iBox->delivery_box_id,
                                'account_id' => $accountId,
                                'area_id' => $iBox->area_id,
                                'warehouse_id' => $iBox->warehouse_id,
                                'storage_total' => $transferNum,
                                'num_per_box' => $iBox->num_per_box,
                                'psku_id' => $iBox->psku_id,
                                'storage_at' => $iBox->storage_at,
                            ]);
                    }
                    $iBoxFnSku = InventoryBoxFNSku::query()
                        ->firstOrNew(
                            [
                                'account_id' => $accountId,
                                'fnsku' => $fnsku,
                                'warehouse_id' => $iBox->warehouse_id,
                            ],[
                                'psku_id' => $iBox->psku_id,
                            ]
                        );
                    $iBoxFnSku->instant += $transferNum * $iBox->num_per_box;
                    $iBoxFnSku->save();
                    $count++;
                    BoxTranLog::logs($iBox->batch_no,$iBox->box_no,['o' => $iBox->account_id,'i' => $accountId],['o' => $iBox->fnsku,'i' => $fnsku],$transferNum);
                }
                $iBox->out_total += $total;
                $o_flag = $iBox->save();
                if(count($temp) == $count && $o_flag){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            return response()->json([
                'status' => !empty($msg) ? false : true,
                'message' => !empty($msg) ? implode(PHP_EOL,$msg).'数量超出' : '操作成功！'
            ]);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 拆箱
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function split($param){

        try{

            $details = $param['detail'];
            $msg = [];

            foreach($details as $id => $item){

                DB::beginTransaction();
                //中转库存仓库
                $inventoryBoxObj = InventoryBox::query()->lockForUpdate()->find($id);
                if(!$inventoryBoxObj){
                    DB::rollBack();
                    continue;
                }

                $inventoryBefore = $inventoryBoxObj->out_total; //原出库箱数
                $splitBoxNum = abs($item['split_box_num']); //拆箱数
                $instantNum = $splitBoxNum * $inventoryBoxObj->num_per_box; //库存数量 = 单箱数量*拆箱箱数
                if ($inventoryBoxObj->storage_total < $splitBoxNum || $splitBoxNum <= 0) {
                    $msg[] = $inventoryBoxObj->fnsku;
                    DB::rollBack();
                    continue;
                }

                //一件代发库存
                $dropshippingFnskuObj = DropshippingInventoryFnsku::query()
                    ->where('account_id', $item['account_id'])
                    ->where('warehouse_id', $item['warehouse_id'])
                    ->where('fnsku', $item['fnsku'])
                    ->where('psku_id', $item['psku_id'])
                    ->first();
                if($dropshippingFnskuObj){
                    //存在,更新
                    $dropshippingFnskuObj->instant += $instantNum;
                    if(!$dropshippingFnskuObj->save()){
                        DB::rollBack();
                        continue;
                    }
                }else{
                    //不存在,创建
                    DropshippingInventoryFnsku::query()
                        ->create([
                            //'area_id' => $inventoryBoxObj->area_id,
                            //'country_id' => $inventoryBoxObj->country_id,
                            //'seller_sku' => $inventoryBoxObj->xxx,
                            'account_id' => $item['account_id'],
                            'fnsku' => $item['fnsku'],
                            'warehouse_id' => $item['warehouse_id'],
                            'psku_id' => $item['psku_id'],
                            'instant' => $instantNum,
                        ]);
                }

                //日志
                $logData = [];
                $logData['batch_no'] = $inventoryBoxObj->batch_no;
                $logData['box_no'] = $inventoryBoxObj->box_no;
                $logData['fnsku'] = $inventoryBoxObj->fnsku;
                $logData['warehouse_id'] = $inventoryBoxObj->warehouse_id;
                $logData['account_id'] = $inventoryBoxObj->account_id;
                $logData['psku_id'] = $inventoryBoxObj->psku_id;
                $logData['box_num_before'] = $inventoryBefore;
                $logData['num_per_box'] = $inventoryBoxObj->num_per_box;
                $logData['split_box_num'] = $splitBoxNum;
                DropshippingLog::logs($logData);

                //更新中转库存仓库
                $inventoryBoxObj->out_total += $splitBoxNum; //出库箱数
                if(!$inventoryBoxObj->save()){
                    DB::rollBack();
                }
            }

            DB::commit();
            return response()->json([
                'status' => !empty($msg) ? false : true,
                'message' => !empty($msg) ? implode(PHP_EOL,$msg).'数量超出' : '操作成功！'
            ]);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

}
